#!/usr/bin/env python

import datetime
from argparse import ArgumentParser
from __init__ import __version__
from utils import get_mysql_conf
import pymysql
from utils import ip_to_long


def get_options():
    usage = "Query an IP's Geo Information"
    opt_format_help = '''set output format. %%c will be replaced with country,
 %%s will be replaced with state or province,%%l will be replaced with city.
 %%i will be replaced with IP. "%%c, %%s, %%l" is default'''
    parser = ArgumentParser(version="%prog " + __version__, description=usage)
    parser.add_argument("ip", help="ip")
    parser.add_argument('-f', '--format', default="%c, %s, %l", help=opt_format_help)
    parser.add_argument('-c', '--clean', action='store_false', default='false',
                        help='output with no query time information')
    args = parser.parse_args()
    return args, args.ip


def query_ip_geo_online(ip):
    pass


def query_ip_geo(ip):
    ip = ip_to_long(ip)
    host, port, username, password, db, table_name = get_mysql_conf()
    connection = pymysql.connect(host=host,
                                 user=username,
                                 password=password,
                                 db=db,
                                 charset='utf8mb4',
                                 cursorclass=pymysql.cursors.DictCursor)
    try:
        with connection.cursor() as cursor:
            query_sql = "SELECT * FROM `" + table_name + "` WHERE `ip_end`>=%s limit 1"
            cursor.execute(query_sql, (ip,))
            result = cursor.fetchone()
            ip_start = result['ip_start']
            ip_end = result['ip_end']
            if ip_start <= ip <= ip_end:
                return result
            else:
                return None
    finally:
        connection.close()


def main():
    options, ip = get_options()
    output_format = options.format
    start = datetime.datetime.now()
    result = query_ip_geo(ip)
    if result:
        country = result['country'] or ''
        state = result['stateprov'] or ''
        city = result['city'] or ''
        output_format = output_format.replace('%c', country)
        output_format = output_format.replace('%s', state)
        output_format = output_format.replace('%l', city)
        output_format = output_format.replace('%i', ip)
        print output_format
        print 'Query time:', datetime.datetime.now() - start
    else:
        print "not found"


if __name__ == '__main__':
    main()
